import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast, Button, Card } from 'antd-mobile';
import TencentMap from '../components/TencentMap_test';
import { API_CONFIG, request } from '../config/api';
import { gitAddress, MAP_CONFIG } from '../config/map';
import axios from 'axios';
import './Home.css';

// 地址转经纬度
const geocodeAddress = async (address) => {
  if (typeof address !== 'string') {
    console.error('地理编码传入的不是字符串:', address);
    return null;
  }
  try {
    const url = `/api/map/ws/geocoder/v1/?address=${encodeURIComponent(address)}&key=${MAP_CONFIG.API_KEY}`;
    const res = await fetch(url);
    const data = await res.json();
    if (data.status === 0) {
      return data.result.location; // { lat, lng }
    } else {
      throw new Error('地理编码失败');
    }
  } catch (err) {
    console.error('地址解析失败:', err);
    return null;
  }
};

function Home() {
  const [onlineStatus, setOnlineStatus] = useState(false);
  const [todayStats, setTodayStats] = useState({
    orders: 0,
    earnings: 0,
    rating: 4.9
  });
  const [currentLocation, setCurrentLocation] = useState(null);
  const [locationAddress, setLocationAddress] = useState('');
  const [orderInfo, setOrderInfo] = useState(null);

  const [onlineTime, setOnlineTime] = useState(0);
  const [sessionStartTime, setSessionStartTime] = useState(null);
  const timerRef = useRef(null);

  const [riderId, setRiderId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const [announcements] = useState([
    '🔥 保持在线状态，提高接单成功率',
    '📦 新用户首单立减5元',
    '⭐ 完成订单可获得积分奖励',
    '🚀 配送高峰期，建议提前上线',
    '💡 遇到问题可联系在线客服'
  ]);

  const [currentAnnouncement, setCurrentAnnouncement] = useState(0);
  const [isPaused, setIsPaused] = useState(false);

  const navigate = useNavigate();

  // 格式化时间
  const formatTime = (seconds) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}小时${minutes}分`;
  };

  // 获取订单信息 + 地址转坐标
  const fetchOrderInfo = async () => {
    const currentOrderId = localStorage.getItem('currentOrderId');
    if (currentOrderId) {
      const currentOrder = JSON.parse(currentOrderId);
      if (currentOrder) {
        const response = await axios.get(`${API_CONFIG.ORDER.LIST}`, {
          params: {
            page: 1,
            pageSize: 1,
            _id: currentOrder
          }
        });

        if (response.data) {
          const order = response.data.data.list[0];
          console.log('🚀 ~ 当前订单信息:', order);

          // 地址转经纬度
          const from = await geocodeAddress(String(order.senderAddress));
          const to = await geocodeAddress(String(order.receiverAddress));

          if (from && to) {
          setOrderInfo({
            ...order,
            from,
            to
          });
        } else {
          setOrderInfo(null);
        }
      }}
    }
  };

  useEffect(() => {
    fetchOrderInfo();
  }, []);

  // 开始接单
  const handleStartWorking = async () => {
    if (!riderId) {
      Toast.show({ content: '请先登录骑手账户', duration: 2000 });
      return;
    }
    if (!currentLocation) {
      Toast.show({ content: '请先获取位置信息', duration: 2000 });
      return;
    }

    setIsLoading(true);
    try {
      const response = await request(API_CONFIG.RIDER.ONLINE, {
        method: 'POST',
        body: JSON.stringify({
          riderId: riderId,
          location: {
            lat: currentLocation.lat,
            lng: currentLocation.lng,
            address: currentLocation.address || ''
          }
        })
      });

      if (response.code === 0) {
        setOnlineStatus(true);
        setSessionStartTime(Date.now());

        const currentOnlineTime = response.data.onlineTime || onlineTime || 0;
        setOnlineTime(currentOnlineTime);

        timerRef.current = setInterval(() => {
          setOnlineTime(prev => prev + 1);
        }, 1000);

        updateLocalRiderInfo({
          onlineStatus: true,
          workStatus: 'IDLE',
          onlineTime: currentOnlineTime,
          lastOnlineAt: new Date().toISOString(),
          todayOnlineDate: new Date().toISOString().split('T')[0]
        });

        Toast.show({ content: '已开始接单，计时开始', duration: 2000 });
      } else {
        Toast.show({ content: response.message || '上线失败', duration: 2000 });
      }
    } catch (error) {
      console.error('上线失败:', error);
      Toast.show({ content: '上线失败，请稍后重试', duration: 2000 });
    } finally {
      setIsLoading(false);
    }
  };

  // 暂停接单
  const handleStopWorking = async () => {
    if (!riderId) {
      Toast.show({ content: '请先登录骑手账户', duration: 2000 });
      return;
    }

    setIsLoading(true);
    try {
      const response = await request(API_CONFIG.RIDER.OFFLINE, {
        method: 'POST',
        body: JSON.stringify({ riderId: riderId })
      });

      if (response.code === 0) {
        setOnlineStatus(false);
        setSessionStartTime(null);
        setOnlineTime(response.data.totalOnlineTime || 0);

        if (timerRef.current) {
          clearInterval(timerRef.current);
          timerRef.current = null;
        }

        updateLocalRiderInfo({
          onlineStatus: false,
          workStatus: 'OFFLINE',
          onlineTime: response.data.totalOnlineTime || 0
        });

        Toast.show({ content: '已暂停接单，计时停止', duration: 2000 });
      } else {
        Toast.show({ content: response.message || '下线失败', duration: 2000 });
      }
    } catch (error) {
      console.error('下线失败:', error);
      Toast.show({ content: '下线失败，请稍后重试', duration: 2000 });
    } finally {
      setIsLoading(false);
    }
  };

  // 模拟统计数据
  useEffect(() => {
    setTodayStats({
      orders: 12,
      earnings: 128.50,
      rating: 4.9
    });
  }, []);

  // 通告轮播
  useEffect(() => {
    if (isPaused) return;
    const timer = setInterval(() => {
      setCurrentAnnouncement((prev) => (prev + 1) % announcements.length);
    }, 3000);
    return () => clearInterval(timer);
  }, [announcements.length, isPaused]);

  useEffect(() => {
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, []);

  const handleAnnouncementClick = (index) => {
    setCurrentAnnouncement(index);
    setIsPaused(true);
    setTimeout(() => setIsPaused(false), 3000);
  };

  const handleLocationChange = async (location) => {
    setCurrentLocation(location);
    try {
      const res = await gitAddress(location);
      setLocationAddress(res || '未获取到详细地址');
    } catch {
      setLocationAddress('地址解析失败');
    }

    if (onlineStatus && riderId) {
      try {
        await request(API_CONFIG.RIDER.UPDATE_LOCATION, {
          method: 'POST',
          body: JSON.stringify({
            riderId: riderId,
            location: {
              lat: location.lat,
              lng: location.lng,
              address: location.address || ''
            }
          })
        });

        updateLocalRiderInfo({
          currentLocation: {
            lat: location.lat,
            lng: location.lng,
            address: location.address || '',
            updateTime: new Date().toISOString()
          }
        });
      } catch (error) {
        console.error('位置同步失败:', error);
      }
    }

    Toast.show({ content: '位置信息已更新', duration: 2000 });
  };

  const updateLocalRiderInfo = (updates) => {
    try {
      const storedRiderInfo = localStorage.getItem('riderInfo');
      if (storedRiderInfo) {
        const riderInfo = JSON.parse(storedRiderInfo);
        const updatedRiderInfo = { ...riderInfo, ...updates };
        localStorage.setItem('riderInfo', JSON.stringify(updatedRiderInfo));
      }
    } catch (error) {
      console.error('更新localStorage失败:', error);
    }
  };

  const fetchRiderStatus = async (id) => {
    try {
      const response = await request(API_CONFIG.RIDER.GET_STATUS(id));
      if (response.code === 0) {
        const { currentOrderId: order, onlineStatus: status, onlineTime: time, workStatus, currentLocation, todayOnlineDate, lastOnlineAt } = response.data;
        setOnlineStatus(status);

        if (status) {
          let finalOnlineTime = time || 0;
          if (lastOnlineAt) {
            const lastOnline = new Date(lastOnlineAt);
            const now = new Date();
            const elapsedSeconds = Math.floor((now - lastOnline) / 1000);
            finalOnlineTime = time + elapsedSeconds;
          }
          setOnlineTime(finalOnlineTime);
          setSessionStartTime(new Date());
          timerRef.current = setInterval(() => {
            setOnlineTime(prev => prev + 1);
          }, 1000);
        } else {
          if (timerRef.current) {
            clearInterval(timerRef.current);
            timerRef.current = null;
          }
          setSessionStartTime(null);
          setOnlineTime(time || 0);
        }

        updateLocalRiderInfo({
          onlineStatus: status,
          workStatus: workStatus || 'OFFLINE',
          onlineTime: time || 0,
          currentLocation: currentLocation || null,
          todayOnlineDate: todayOnlineDate || null,
          lastOnlineAt: lastOnlineAt || null,
          order: order
        });
      }
    } catch (error) {
      console.error('获取骑手状态失败:', error);
    }
  };

  useEffect(() => {
    const storedRiderInfo = localStorage.getItem('riderInfo');
    if (storedRiderInfo) {
      try {
        const riderInfo = JSON.parse(storedRiderInfo);
        setRiderId(riderInfo._id);
        fetchRiderStatus(riderInfo._id);
      } catch (error) {
        console.error('解析骑手信息失败:', error);
      }
    }
  }, []);

  return (
    <div className="home-container">
      {/* 顶部通告栏 */}
      <div className="announcement-bar">
        <div className="announcement-icon">📢</div>
        <div className="announcement-content">
          <div className="announcement-text" style={{ transform: `translateY(-${currentAnnouncement * 100}%)` }}>
            {announcements.map((announcement, index) => (
              <div key={index} className="announcement-item">
                {announcement}
              </div>
            ))}
          </div>
        </div>
        <div className="announcement-dots">
          {announcements.map((_, index) => (
            <span
              key={index}
              className={`dot ${index === currentAnnouncement ? 'active' : ''}`}
              onClick={() => handleAnnouncementClick(index)}
            ></span>
          ))}
        </div>
        <div className="announcement-status">
          {isPaused ? '⏸️' : '▶️'}
        </div>
      </div>

      {/* 状态栏 */}
      <div className="status-bar">
        <div className="status-info">
          <div className="status-text">
            <span className={`status-dot ${onlineStatus ? 'online' : 'offline'}`}></span>
            {onlineStatus ? '在线接单中' : '离线状态'}
          </div>
          <div className="status-time">
            今日在线: {formatTime(onlineTime)}
            {!riderId && <div className="login-tip">⚠️ 请先登录骑手账户</div>}
            {riderId && <div className="rider-info">✅ 骑手账户已登录</div>}
          </div>
        </div>
        <Button
          className={`status-toggle ${onlineStatus ? 'online' : 'offline'}`}
          onClick={onlineStatus ? handleStopWorking : handleStartWorking}
          loading={isLoading}
          disabled={isLoading || !riderId}
        >
          {onlineStatus ? '暂停接单' : '开始接单'}
        </Button>
      </div>

      {/* 地图 */}
      <TencentMap 
        onLocationChange={handleLocationChange}
        orderPolyline={orderInfo?.from && orderInfo?.to ? { from: orderInfo.from, to: orderInfo.to } : null}
      />

      {/* 订单信息 */}
      {orderInfo ?(
        <Card className="order-card" style={{ marginTop: 16 }}>
          <h4>📦 当前订单信息</h4>
          <div><strong>订单号:</strong> {orderInfo.orderNo}</div>
          <div><strong>类品:</strong> {orderInfo.shopname}</div>
          <div><strong>发件人:</strong> {orderInfo.senderName}</div>
          <div><strong>收件人:</strong> {orderInfo.receiverName}</div>
          <div><strong>发件地址:</strong> {orderInfo.senderAddress}</div>
          <div><strong>收件地址:</strong> {orderInfo.receiverAddress}</div>
          <div><strong>发件人手机:</strong> {orderInfo.sendphone}</div>
          <div><strong>收件人电话:</strong> {orderInfo.receiverphone}</div>
        </Card>
      ):<Card>当前没有订单</Card>}

      {/* 位置信息 */}
      {currentLocation && (
        <Card className="location-card">
          <h4>📍 当前位置信息</h4>
          <p><strong>地址:</strong> {locationAddress || '未获取到地址'}</p>
          <p><strong>状态:</strong> {onlineStatus ? '🟢 在线接单中' : '🔴 离线状态'}</p>
          <Button
            size="small"
            onClick={() => {
              navigator.clipboard.writeText(
                `纬度: ${currentLocation.lat.toFixed(6)}, 经度: ${currentLocation.lng.toFixed(6)}`
              ).then(() => {
                Toast.show({ content: '位置信息已复制', duration: 1500 });
              });
            }}
          >
            📋 复制坐标
          </Button>
        </Card>
      )}

      {/* 今日统计 */}
      <Card className="stats-card">
        <div className="stats-grid">
          <div className="stat-item">
            <div className="stat-number">{todayStats.orders}</div>
            <div className="stat-label">今日订单</div>
          </div>
          <div className="stat-item">
            <div className="stat-number">¥{todayStats.earnings}</div>
            <div className="stat-label">今日收入</div>
          </div>
          <div className="stat-item">
            <div className="stat-number">{todayStats.rating}</div>
            <div className="stat-label">评分</div>
          </div>
        </div>
      </Card>
    </div>
  );
}

export default Home;
